package com.umeox.watch.moto.apiclient.http;


import android.text.TextUtils;
import android.util.Log;

import com.umeox.watch.moto.apiclient.BuildConfig;
import com.umeox.watch.moto.apiclient.model.TokenDTO;
import com.umeox.watch.moto.apiclient.utils.GsonUtils;

import java.io.IOException;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

class TokenInterceptor implements Interceptor {
    private static final String TAG = TokenInterceptor.class.getSimpleName();

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj.getClass().getName().equals(getClass().getName());
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        HttpUrl url = originalRequest.url();

        boolean hasTokenParameter = false;
        String tokenParameterName = "access_token";
        Set<String> params = url.queryParameterNames();
        for (String param : params) {
            if (tokenParameterName.equals(param)) {
                hasTokenParameter = true;
                break;
            }
        }

        if (hasTokenParameter) {
            if (TextUtils.isEmpty(url.queryParameter(tokenParameterName))) {
                Log.w(TAG, "Token参数为空，重新请求");
                String token = getNewToken();
                HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
                urlBuilder.setQueryParameter(tokenParameterName, token);
                originalRequest = originalRequest.newBuilder().url(urlBuilder.build()).build();
            }

            Response response = chain.proceed(originalRequest);
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            if (isTokenExpired(content)) {
                Log.w(TAG, "Token已过期，刷新Token");
                String token = getNewToken();
                HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
                urlBuilder.setQueryParameter(tokenParameterName, token);
                return chain.proceed(originalRequest.newBuilder().url(urlBuilder.build()).build());
            } else {
                return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
            }
        }

        return chain.proceed(originalRequest);
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(String response) {
        if (!TextUtils.isEmpty(response)) {
            org.json.JSONObject result = null;
            try {
                result = GsonUtils.toJSONObject(response);
                if (result != null) {
                    return result.has("status") && "40102".equals(result.getString("status"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken() {
        // 通过获取token的接口，同步请求接口
        TokenDTO tokenDTO = WaasApiWrapper.getInstance().refreshToken();
        if (BuildConfig.DEBUG) {
            Log.d(TAG ,"-getNewToken>>>>" + tokenDTO);
        }
        return tokenDTO != null ? tokenDTO.access_token : "";
    }
}
